<template>
  <div class="zs-table-page-container">
    <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
      <span>
        <el-select v-model="queryParams.groupCode" filterable clearable class="zs-select-md zs-space-right-sm"
          placeholder="集团">
          <el-option v-for="item in dictObj.DASH_TOTAL_CORP" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
        <el-select multiple v-model="queryParams.projectCode" filterable clearable class="zs-select-md zs-space-right-sm"
          placeholder="项目名称" :disabled="queryParams.fromatCode == 'ZT'">
          <el-option v-for="item in projectList" :key="item.biProjectCode" :label="item.biProjectName"
            :value="item.biProjectCode" />
        </el-select>
        <el-date-picker @change="queryList" class="zs-space-right-sm" v-model="queryParams.yearMonth" type="month"
          placeholder="日期" :clearable="false" value-format="YYYY-MM" />
        <!-- :prefix-icon="DateBeforeIcon" -->
        <el-button class="zs-btn-plain" @click="queryList()">查询</el-button>
      </span>
      <span style="width: 500px;overflow:auto" class="zs-layout-flex-row">
        <div :class="{
          'db-btn': true,
          'zs-space-right-sm': true,
          'db-btn-primary': item.dictValue == queryParams.fromatCode,
          'btn-disabled': item.dictValue == 'ZT' && queryParams.projectCode?.length > 0
        }" @click="changeTab(item)" v-for="(item, index) in bizTypeList" :key="index">{{ item.dictLabel }}</div>
      </span>
    </div>
    <div class="zs-card zs-table-page-content">
      <hsTableV2
        fixed
        rowKey="subjectNum"
        :loading="tableData.loading" 
        :columns="tableData.columns"
        :data="tableData.data"
        :headerHeight="72"
        isMultistageHeader
        :multistageHeaderData="tableData.multistageData"
        :rowClassFun="tableData.rowClass"
        />
      <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTypeLabel == '整体' || curTypeLabel == '餐饮'">*单位：万元</div>
      <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTypeLabel == '商业'">*单位：万元；万人次；㎡</div>
      <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTypeLabel == '办公' || curTypeLabel == '产业'">*单位：万元；㎡</div>
      <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTypeLabel == '酒店'">*单位：万元；元</div>
      <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTypeLabel == '其他'">*单位：万元；㎡</div>
      <div class="zs-text-gray-dark zs-text-sm zs-space-top" v-if="curTypeLabel == '综合体'">*单位：万元；万人次；㎡</div>
        <!-- isRowSpan
        :colSpanIndex="[0]" -->
      <!-- customRowClassFun -->
    </div>
		<DealogDesc v-if="descShowDrawer" :isShow="descShowDrawer" :projectCode="biProjectCode" :yearmonth="queryParams.yearMonth" @close="closeDrawer"> </DealogDesc>
  </div>
</template>

<script setup lang="jsx">
// import TableV2 from '@/components/tableV2.vue';
// import projectListApi from '@/api/Property/projectList'
import DealogDesc from "./components/dialogDesc.vue"
import { toThousands } from '@/utils/number-util'
import { queryBusinessSummaryProjectListApi, getProjectDropDownListApi } from '@/api/BusinessSummary/projectList'
import { ref, reactive } from 'vue'
import { useStore } from "vuex"
import { useRouter } from 'vue-router'
const router = useRouter()
let store = useStore()

let dictObj = store.getters.getDictObj(['DASH_TOTAL_DEPART','DASH_TOTAL_CORP'])
const bizTypePermiList = ref([{ label: '商业', id:"BUSINESS", permi: 'p_btn_901_jingyingxiangmu_shangye' }, { label: '办公', id: 'OFFICE', permi: 'p_btn_901_jingyingxiangmu_bangong' }, { label: '产业', id: 'INDUSTRY', permi: 'p_btn_901_jingyingxiangmu_chanye' }, { label: '酒寓', id: 'HOTEL', permi: 'p_btn_901_jingyingxiangmu_jiuyu' }, { label: '餐饮', id: 'CATERING', permi: 'p_btn_901_jingyingxiangmu_canyin' }])

let queryParams = reactive({
  groupCode:'',
  projectCode: [],
  yearMonth:'',
  fromatCode: 'ZT'
})
// 业态按钮按钮数据
const bizTypeList = ref([
  { dictValue: 'ZT', dictLabel: '整体' },
  ...dictObj.DASH_TOTAL_DEPART
])
const curTypeLabel = ref('整体')
function changeTab (item) { 
  curTypeLabel.value = item.dictLabel
  if (item.dictValue == 'ZT' && queryParams.projectCode?.length > 0) {
    return
  }
  queryParams.fromatCode = item.dictValue
  queryList()
  getProjectDownList()
}


let tableData = reactive({
  loading: false,
  data: [],
  multistageData:null,
  columns: [
    { key: 'subjectName', align: "left", title: '指标', fixed:'left', width: 205, minWidth: 205, 
      // colSpan: ({ rowData }) => {if (rowData.curType) return 15 },
      cellRenderer: ({ rowData }, emptyMark) => {
          if (rowData.subjectName) {
            return <span>{rowData.subjectName}</span>
          } else {
            <span>{ emptyMark }</span>
          }
        } },
  ],
  rowClass: ({ rowData }) => {
    let classArr = []
    if (rowData.curType) {
      classArr.push('row-project-title')
    } else {
      classArr.push('row-white')
    }
    if(rowData.isHaveBackClass){
      classArr.push('blue-back')
    } 
    return classArr.join(' ')
  },
})


function queryList () {
  tableData.loading = true
  let params = Object.assign({}, queryParams)
  params.groupCode = params.groupCode || 'QB'
  params.projectCode = params.projectCode?.length > 0 ? params.projectCode.join(',') : '全部'
  if (params.fromatCode == 'ZT') {
    delete params.projectCode
  }
  // params.fromatCode = 'BUSINESS'
  queryBusinessSummaryProjectListApi(params).then(res=>{
    let resData = res.data
    if(resData.code == 200){
      if (resData.data && resData.data.length > 0) {
        let { curMultistageData, curColumns, curTableData } = initCloumns(resData.data)
        tableData.multistageData = curMultistageData
        tableData.columns = [ tableData.columns[0],...curColumns]
        tableData.data = curTableData
      } else {
        tableData.data = []
      }
    }
    tableData.loading = false
  })
}
queryList()

function initCloumns (initData) {
  if (!queryParams.yearMonth) queryParams.yearMonth =  initData[0].yearMonth
  let windowWidth = document.documentElement.scrollWidth
  let celWidth = 0
  let curMultistageData = {}
  const yearmonth = initData[0].yearMonth
  const year = yearmonth.split('-')[0]
  let month = yearmonth.split('-')[1]
  month[0] == 0 ? month = month.substring(1, 2) : ''
  let curMultistageFirstArr = [
    {key:'month',title:`${year}年${month}月`},
    {key:'accMonth',title:`${year}年1-${month}月`},
    {key:'year',title:`${year}年度`},
  ]
  celWidth = (windowWidth - 138 - 205 - 125) / (curMultistageFirstArr.length * 5 - 3)
  curMultistageFirstArr.forEach((el,index)=>{
    const startIndex = index * 5 + 1
    let indexArr = [startIndex, startIndex + 1, startIndex + 2, startIndex + 3, startIndex + 4]
    curMultistageData[el.key] = {
      key:el.key,
      title: el.title,
      childrenIndex: el.key !== 'year' ? indexArr : indexArr.splice(0,3),
    }
  })
  let curColumns = []
  for(let item of curMultistageFirstArr){
    let parentKey = item.key
    let columnsTitle = [
      {parentKey,key:parentKey+'Budget',title:'预算'},
      {parentKey,key:parentKey+'Actual',title:'实际'},
      {parentKey,key:parentKey+'Pc',title:'完成率'},
      {parentKey,key:parentKey+'Erlier',title:'同比'},
      {parentKey,key:parentKey+'BreachValue',title:'缺口'},
    ]
    if (parentKey == 'year') {
      columnsTitle.splice(3,2)
    }
    columnsTitle.forEach(coloumnItem=>{
      let newData = {
        key:coloumnItem.key,
        title:coloumnItem.title,
        align: "right",
        parentKey:coloumnItem.parentKey,
        width: coloumnItem.key == "yearPc" ? 125 : celWidth > 85 ? celWidth : 85,
        minWidth:celWidth > 85 ? celWidth : 85,
        cellRenderer: ({ rowData, rowIndex }) => {
          if (rowData[coloumnItem.key]) {
            return <span class={{'zs-text-red':(coloumnItem.key == 'monthPc' && rowData.monthWclRed == 1) || (coloumnItem.key == 'accMonthPc' && rowData.accWclRed == 1), 'tooltip-txt': true}}>{
                      toThousands(rowData[coloumnItem.key])
                    }</span>
                  
          } else {
            // 商业 办公 产业 酒寓 有明细说明按钮
            let isShow = ["BUSINESS","OFFICE","INDUSTRY","HOTEL"].includes(queryParams.fromatCode)
            if (isShow && rowData.id != 0 && rowData.curType == 'projectTitle' && coloumnItem.key == "yearPc" ) {
              if(rowData.isLink) {
                return <template class={'zs-layout-flex-row zs-layout-items-center dashboard-property-projectAll-row-btns'}>
                    <el-button class="zs-link" link size="small" onClick={() => { goDetail(rowIndex) }}>明细</el-button>
                    <span class="zs-text-gray-light zs-space-left-sm zs-space-right-sm">|</span>
                    <el-button class="zs-link" link size="small" onClick={() => { openDialog(rowIndex) }}>说明</el-button>
                </template>
              }else {
                return <template class={'zs-layout-flex-row zs-layout-items-center dashboard-property-projectAll-row-btns'}>
                    <el-button class="zs-link" link size="small" onClick={() => { openDialog(rowIndex) }}>说明</el-button>
                </template>
              }
            } else {
              <span></span>
            }
          }
        }
      }
      curColumns.push(newData)
    })
  }
  let curTableData = []
  let curId = 0
  initData.forEach((tableDataItem)=>{
    let newData = {
      id: curId++,
      biProjectCode:tableDataItem.biProjectCode || '',
      biMappingProjectCode:tableDataItem.biMappingProjectCode || '',
      subjectName:tableDataItem.title,
      isHaveBackClass: queryParams.fromatCode == 'ZT' ? (tableDataItem.title.indexOf('整体') !== -1) : tableDataItem.title.indexOf('合计') !== -1,
      curType: 'projectTitle',
      isLink: tableDataItem.isLink
    }
    curTableData.push(newData)
    if (tableDataItem.dataList?.length > 0) {
      tableDataItem.dataList.forEach(childrenItem=>{
        let childrenData = {
          id: curId++,
          isHaveBackClass: queryParams.fromatCode == 'ZT' ? (tableDataItem.title.indexOf('整体') !== -1) : tableDataItem.title.indexOf('合计') !== -1,
          ...childrenItem
        }
        curTableData.push(childrenData)
      })
    }
  })

  return { curMultistageData, curColumns, curTableData }
}

let projectList = ref([])
function getProjectDownList() {
  getProjectDropDownListApi(queryParams.fromatCode).then(res=>{
    let resData = res.data
    if(resData.code == 200){
      projectList.value = resData.data
    }
  })
}
getProjectDownList()

//明细
const goDetail = (rowIndex) => {
    if (tableData.data[rowIndex]) {
        const data = tableData.data[rowIndex]
        let target = bizTypePermiList.value.find(item => item.id == queryParams.fromatCode)
        let tabPermi = target.permi || ''
        console.log(target)
        router.push({
          path: '/page/routeController/index',
          query: {
              rid: 'Manage/Business/budgetcAhievement/budgetcAhievement',
              rTitle: '预算对标',
              biProjectCode: data.biMappingProjectCode,
              tabPermi: tabPermi,
              type: tabPermi == 'p_btn_901_jingyingxiangmu_shangye' || tabPermi == 'p_btn_901_jingyingxiangmu_bangong'  || tabPermi == 'p_btn_901_jingyingxiangmu_chanye'  ? 1 : 2 // 商办产1，酒寓2
          },
        })
    }
}

//说明
let biProjectCode = ref("")
let descShowDrawer = ref(false)
const openDialog = (rowIndex) => {
  if (tableData.data[rowIndex]) {
    const data = tableData.data[rowIndex]
    console.log(data)
    biProjectCode.value = data.biMappingProjectCode
    descShowDrawer.value = true
  }
}
const closeDrawer = data => {
  descShowDrawer.value = data.isShow;
};

</script>

<style lang="scss" scoped>
.btn-disabled{
  opacity: 0.8;
  color: #a8abb2;
  cursor: no-drop;
}
:deep(.el-table-v2 .row-project-title){
  border-top: 1px solid #b9bac0;
  background: #fbfbfb;
  font-weight: 600;
}
:deep(.el-table-v2 .row-white){
  background: white;
}
:deep(.el-table-v2 .blue-back){
  background: #EBF6FF
}
:deep(.el-table-v2__row-cell) {
  overflow: initial;
}
:deep(text-hide) {
  overflow: initial !important;
}
</style>
